<template>
  <app-page>
    <view :id="id">
      <view class="sign-info-wrap">
        <view class="sign-info">
          <view class="my-coin">
            <text>我的K币</text>
            <text class="num">{{ userInfo ? `${userInfo.virtualCoins || 0}` : '--' }}</text>
          </view>
          <view class="sign-icon">
            <view class="sign-icon-wrap">
              <image class="icon" src="/static/images/personal/sign-in-icon-mini.svg" mode="scaleToFill"></image>
              <text>签到</text>
            </view>
          </view>
        </view>
        <view class="bg">
          <image class="img" src="/static/images/personal/sign-in-top-bg.png" mode="scaleToFill"></image>
        </view>
      </view>
      <view class="sign-in-vessel-box">
        <view class="sign-in-tip">
          <view>
            <text>已连续签到</text>
            <text class="day">{{ sustainSignInCount }}</text>
            <text>天~</text>
          </view>
          <view class="sign-in-tip-other">
            <text>继续签到得更多奖励</text>
          </view>
        </view>
        <view class="week-vessel-box">
          <view v-for="(item, index) in signInWeekList" :key="index" class="week-box" :class="item.isSign ? 'active-week-box' : ''">
            <view class="icon-box">
              <image v-if="item.isSign === 1" key="image-1" src="/static/public/ico_diamond.png" mode="scaleToFill"></image>
              <image v-else key="image-2" src="/static/public/ico_diamond2.png" mode="scaleToFill"></image>
            </view>
            <view class="week-box">
              <text v-if="item.isSign === 0 && currentDayCpt - 1 === index" key="text-1" class="wait-sign-in">待签</text>
              <text v-else key="text-2">{{ item.isSign ? `+${item.virtualCoins}` : item.weekDayName }}</text>
            </view>
          </view>
        </view>
        <view class="button-box">
          <button class="button" :loading="signInButtLoading" @click="signInClick">
            {{ todaySignInState ? '已签到' : '立即签到' }}
          </button>
        </view>
      </view>
    </view>
    <mxp-refresh-page ref="mxpRefreshPageRef" :emptyHeight="emptyHeight" :reachBottom="true" :queryData="queryList">
      <view v-if="signInDetailsList.length > 0" class="signin-details-vessel-box">
        <view class="title-box">
          <text class="title">签到记录</text>
        </view>
        <view class="signin-details-list">
          <view v-for="(item, index) in signInDetailsList" :key="index" class="item">
            <view class="histoy-item">
              <image class="history-icon" src="/static/images/personal/sign-in-history-icon.svg" mode="scaleToFill"></image>
              <view class="name-box">
                <text class="name">{{ item.signTitle }}</text>
                <text class="date">{{ item.lastSignTime }}</text>
              </view>
            </view>
            <view class="integral-box">
              <text class="integral">+{{ item.virtualCoins }}</text>
            </view>
          </view>
        </view>
      </view>
    </mxp-refresh-page>
  </app-page>
</template>

<script setup lang="ts">
  import { computed, getCurrentInstance, nextTick, ref } from 'vue';
  import AppPage from '@/components/app-page/app-page.vue';
  import { type SignInWeek, type SignRecords, type UserInfo, addSignAxios, getSignInWeekListAxios, getSignRecordsAxios } from '@/api/user';
  import useMxpToastRefHooks from '@/utils/hooks/useToast';
  import { onPullDownRefresh, onReachBottom, onReady } from '@dcloudio/uni-app';
  import { updateUserInfo } from '@/utils/page/user';
  import { useAppStore } from '@/pinia/app';
  import MxpRefreshPage, { type Ins } from '@/mxp-ui/mxp-refresh-page/mxp-refresh-page.vue';
  import { useRefresh } from '@/mxp-ui/mxp-tool/hooks/useHooksRefresh.ts';
  import { getDomSize } from '@/mxp-ui/mxp-tool/utils/dom';
  import mxpGetSysInfoStore from '@/mxp-ui/mxp-tool/store/mxp-store-sys-info';
  import type { $AllSizeUnitStr } from '@/mxp-ui/mxp-tool/types/interface';

  const id = 'sign-module';
  const signModuleHeight = ref(356);
  const sys = mxpGetSysInfoStore().getSysInfo();
  onReady(() => {
    const instance = getCurrentInstance();
    nextTick(async () => {
      const rect = await getDomSize(`#${id}`, instance);
      signModuleHeight.value = rect.height || 356;
    });
  });

  const { mxpRefreshPageRef } = useRefresh(onPullDownRefresh, onReachBottom);

  const appStore = useAppStore();
  const userInfo = computed<UserInfo | undefined>(() => appStore.userInfo);
  const emptyHeight = computed<$AllSizeUnitStr>(() => {
    const h = sys.value.windowHeight - signModuleHeight.value;
    return h > 200 ? `${h}px` : `${200}px`;
  });
  const mxpToastRef = useMxpToastRefHooks();
  const signInWeekList = ref<SignInWeek[]>([]);
  const signInDetailsList = ref<SignRecords[]>([]);

  const todaySignInState = ref(false);
  const signInButtLoading = ref(false);

  /**
   * 获取数据
   */
  async function queryList(ins: Ins) {
    try {
      const promises: any[] = [getSignRecordsAxios(ins.page, ins.size)];
      ins.page <= 1 && promises.push(getSignInWeekListAxios());
      const res = await Promise.all(promises);
      signInDetailsList.value = ins.page > 1 ? signInDetailsList.value.concat(res[0].data.records) : res[0].data.records;
      if (ins.page <= 1) {
        signInWeekList.value = res[1].data;
        let week = new Date().getDay();
        week = week === 0 ? 7 : week;
        todaySignInState.value = Boolean(signInWeekList.value[week - 1]?.isSign === 1);
      }
      ins.setMoreSuccess(res[0].data.records.length, res[0].data.total);
    } catch (error) {
      ins.setMoreEmpty('fail_load', error.msg || '获取数据失败，BD001');
    }
  }

  /** 签到 */
  async function signInClick() {
    if (!signInButtLoading.value && !todaySignInState.value) {
      try {
        signInButtLoading.value = true;
        const res = await addSignAxios();
        let week = new Date().getDay();
        week = week === 0 ? 7 : week;
        if (signInWeekList.value[week - 1]) {
          signInWeekList.value[week - 1]!.isSign = 1;
          signInWeekList.value[week - 1]!.virtualCoins = res.data.virtualCoins;
        }
        signInButtLoading.value = false;
        todaySignInState.value = true;
        signInDetailsList.value.unshift(res.data);
        updateUserInfo(); // 更新个人资料
        mxpToastRef.value?.showSuccess('签到成功');
        mxpRefreshPageRef.value?.setSuccess();
      } catch (error) {
        signInButtLoading.value = false;
        mxpToastRef.value?.showError(error.msg || '签到失败，BD001');
      }
    }

    // TODO
  }

  const currentDay = ref(new Date().getDay());

  const currentDayCpt = computed(() => (currentDay.value === 0 ? 7 : currentDay.value));

  /** 连续签到次数 */
  const sustainSignInCount = computed(() => {
    if (!signInWeekList.value.length) {
      return 0;
    }

    const currentDays = signInWeekList.value.slice(0, currentDayCpt.value);

    if (currentDays.every((v) => v.isSign === 1)) {
      return currentDayCpt.value;
    }

    let sustainDay = 0;

    for (let i = currentDays.length - 1; i > 0; i--) {
      if (currentDays[i]?.isSign === 1) {
        sustainDay++;
      } else {
        break;
      }
    }

    return sustainDay;
  });
</script>

<style lang="scss" scoped>
  @keyframes have-room {
    0% {
      opacity: 1;
      transform: scale(1);
    }

    50% {
      opacity: 0.5;
      transform: scale(1.4);
    }

    100% {
      opacity: 0;
      transform: scale(1.8);
    }
  }
  @keyframes have-room {
    0% {
      opacity: 1;
      transform: scale(1);
    }

    50% {
      opacity: 0.5;
      transform: scale(1.4);
    }

    100% {
      opacity: 0;
      transform: scale(1.8);
    }
  }

  .sign-info-wrap {
    position: relative;
    height: 340rpx;
    background-color: #fcd834;

    .sign-info {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 300rpx;
      padding: 0 30rpx;
    }

    .bg {
      position: absolute;
      bottom: 0rpx;
      z-index: 0;
      width: 100vw;
      height: 138px;

      .img {
        width: 100vw;
        height: 138px;
      }
    }

    .my-coin {
      z-index: 1;
      display: flex;
      flex-direction: column;
      gap: 8rpx;
      font-size: 30rpx;
      font-weight: 500;
      color: #522700;

      .num {
        font-size: 56rpx;
        font-weight: bold;
        color: #522700;
      }
    }

    .sign-icon {
      position: relative;
      z-index: 2;
      width: 140rpx;
      height: 140rpx;
      margin-right: 30rpx;

      &:before {
        position: absolute;
        inset: 0;
        z-index: -1;
        content: '';
        background: #f5fde5;
        border-radius: 50%;
        animation: have-room 3s linear infinite;
      }

      &:after {
        position: absolute;
        inset: 0;
        z-index: -1;
        content: '';
        background: #f5fde5;
        border-radius: 50%;
        animation: have-room 3s linear infinite;
        animation-delay: 1s;
      }

      .sign-icon-wrap {
        display: flex;
        gap: 6rpx;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        font-size: 22rpx;
        color: #522700;
        background-color: #ffffff;
        border-radius: 50%;
      }

      .icon {
        width: 26rpx;
        height: 26rpx;
        margin-right: 4rpx;
      }
    }
  }

  .sign-in-vessel-box {
    position: relative;
    z-index: 1;
    padding: 30rpx;
    margin: 0 30rpx;
    margin-top: -60rpx;
    background: #ffffff;
    border-radius: 20rpx;

    .sign-in-tip {
      font-size: 28rpx;
      font-style: normal;
      font-weight: 600;
      color: #000000;

      .day {
        padding: 0 6rpx;
        color: #ff0000;
      }

      .sign-in-tip-other {
        padding-top: 8rpx;
        font-size: 24rpx;
        font-weight: normal;
        color: #999999;
      }
    }

    .week-vessel-bg {
      width: 130px;
      height: 130px;
      margin-top: -76px;
    }

    .week-vessel-box {
      display: flex;
      flex-flow: row nowrap;
      place-content: center center;
      align-items: center;
      width: 100%;
      margin-top: 36rpx;

      .week-box {
        display: flex;
        flex: 1;
        flex-flow: column nowrap;
        place-content: center center;
        align-items: center;

        .integral-box {
          height: 18px;
          font-size: 16px;
          line-height: 16px;
          color: #ef9406;
        }

        .icon-box {
          display: flex;
          flex-flow: column nowrap;
          place-content: center center;
          align-items: center;
          width: 50rpx;
          min-width: 0;
          height: 50rpx;
          margin: 10rpx 0;
          // background-image: url('/static/images/personal/sign-in-not-ac.png');
          // background-position: center;
          image {
            width: 100%;
            height: 100%;
          }
        }

        .week-box {
          height: 15px;
          font-size: 12px;
          line-height: 15px;
          color: #999999;

          .wait-sign-in {
            padding: 2rpx 6rpx;
            color: #522700;
            background-color: #ffe043;
            border-radius: 4rpx;
          }
        }
      }

      .active-week-box .week-box {
        color: #522700;
      }
    }

    .button-box {
      box-sizing: border-box;
      width: 100%;
      padding-top: 48rpx;

      .button {
        width: 376rpx;
        height: 88rpx;
        font-size: 32rpx;
        font-weight: 600;
        line-height: 88rpx;
        color: #522700;
        background: linear-gradient(126deg, #ffdf00 0%, #fdc000 100%);
        border: 2rpx solid #ffdd39;
        border-radius: 44rpx;
        box-shadow: inset 0rpx 6rpx 16rpx 2rpx #ffffff;

        &:after {
          border: none;
          border-color: transparent;
        }
      }
    }
  }

  /* *
         * 签到记录 */
  .signin-details-vessel-box {
    position: relative;
    box-sizing: border-box;
    width: 690rpx;
    padding: 30rpx;
    margin-top: 15px;
    margin-left: 30rpx;
    background: #ffffff;
    border-radius: 20rpx;

    .title-box {
      width: 100%;

      .title {
        font-size: 28rpx;
        font-weight: 600;
        color: #000000;
      }
    }

    .signin-details-list {
      box-sizing: border-box;
      width: 100%;
      padding: 5px 0;
      overflow: hidden;
      border-radius: 10px;

      .item {
        display: flex;
        flex-flow: row nowrap;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        padding: 15px 0;
        color: #333333;
        border-bottom: 1px solid #f5f5f5;

        &:last-child {
          border-bottom: none;
        }

        .histoy-item {
          display: flex;
          gap: 12rpx;

          .history-icon {
            width: 64rpx;
            height: 64rpx;
          }
        }

        .name-box {
          display: flex;
          flex: 1;
          flex-flow: column nowrap;
          gap: 4rpx;
          padding-right: 15px;

          .name {
            width: 100%;
            font-size: 24rpx;
            color: #333333;
          }

          .date {
            font-size: 10px;
            color: #888888;
          }
        }

        .integral-box .integral {
          font-size: 36rpx;
          font-weight: bold;
          color: #ff5600;
        }
      }

      .no-data-box {
        /* flex布局 */
        display: flex;
        flex-flow: column nowrap;
        place-content: center center;
        align-items: center;
        width: 100%;
        min-width: 0;
        height: 100%;

        .no-data-img {
          width: 100px;
          height: auto;
        }

        .no-data-text {
          margin-top: 10px;
          font-size: 14px;
          color: #888888;
        }
      }
    }
  }
</style>
